var createError = require('http-errors');
var cookieParser = require('cookie-parser');
var logger = require('morgan');



const expressJWT = require('express-jwt')
var express = require('express');
var goodsRouter = require('./routes/goods');
var usersRouter = require('./routes/users');
var path = require('path');
const cors = require('cors');
var app = express();





// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());



// 静态资源
app.use(express.static(__dirname+'/public'));


// 图片
app.use('/upload', express.static('upload'))




// 跨域
app.use(cors())

// token解析认证
app.use(expressJWT({
  secret: 'flag',
  algorithms: ["HS256"]
}).unless({
  path: ['/users/login']
}))



// 路由
app.use('/goods', goodsRouter);
app.use('/users', usersRouter);



// 全局中间件
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});



// 全局错误处理中间件
// error handler
app.use(function(err, req, res, next) {
  console.log('执行全局错误处理中间件！');
  console.log(err);
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
